#include<iostream>
#include<cstdlib>
#include<unistd.h>

bool GetQueryString(std::string &query_string)
{
    //2 没有重定向
    std::string method = getenv("METHOD");
    bool result = false;
    if(method == "GET"){
        query_string = getenv("QUERY_STRING");
        result = true;
    }
    else if(method == "POST"){
        //CGI如何知道从标准输入里面读取多少个字节呢？
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char c = 0;
        while(content_length--){
            read(0, &c, 1);
            query_string.push_back(c);
        } 
        result = true;
    }
    else{
        result = false;
    }
    return result;
}

void CutString(const std::string &src_string, const std::string& sep, std::string &str1, std::string &str2)
{
    auto pos = src_string.find(sep);
    if(pos != std::string::npos){ //找到了
        str1 = src_string.substr(0, pos);
        str2 = src_string.substr(pos+sep.size());
    }
}

int main()
{   
    std::string query_string;
    if(GetQueryString(query_string))
    {
        std::string str1,str2;
        CutString(query_string,"&", str1, str2);
        std::string name1,name2,val1, val2;
        CutString(str1, "=", name1, val1);
        CutString(str2, "=", name2, val2);


        //因为这个是子进程，它的标准输出被重定向了，被重定向到input[1]去了，因此这个我们是看不到的，父进程可以使用input[0]看到
        std::cout<<name1<<" : "<<val1<<std::endl;
        std::cout<<name2<<" : "<<val2<<std::endl;
        // std::cerr<<"--------------"<<name1.size()+name2.size()+val1.size()+val2.size()+2<<std::endl;
        // //这个是可以看到的
        // std::cerr<<name1<<":"<<val1<<std::endl;
        // std::cerr<<name2<<":"<<val2<<std::endl;

        //可能想进行某种计算（计算、搜索、登录等）、想进行某种存储（注册）
        int x = std::stoi(val1.c_str());
        int y = std::atoi(val2.c_str());
        std::cout<<"<html>";
        std::cout<<"<head><meta charset=\"utf-8\"></head>";
        std::cout<<"<body>";
        std::cout<<"<h3> "<<val1<<" + "<< val2<<" = "<<x+y<<"</h3>";
        std::cout<<"<h3> "<<val1<<" - "<< val2<<" = "<<x-y<<"</h3>";
        std::cout<<"<h3> "<<val1<<" * "<< val2<<" = "<<x*y<<"</h3>";
        std::cout<<"<h3> "<<val1<<" / "<< val2<<" = "<<x/y<<"</h3>";
        std::cout<<"</body>";

        std::cout<<"</html>";

    }

    return 0;
}